package com.siashan.toolkit.lock4j.key;

import org.aopalliance.intercept.MethodInvocation;
import org.springframework.context.expression.MethodBasedEvaluationContext;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 默认分布式锁Key生成器
 *
 * @author siashan
 * @since v1.0.1
 */
public class DefaultLockKeyBuilder extends AbstractLockKeyBuilder {

    private static final ParameterNameDiscoverer NAME_DISCOVERER = new DefaultParameterNameDiscoverer();

    /**
     * Spel表达式解析器
     */
    private static final ExpressionParser PARSER = new SpelExpressionParser();

    /**
     * 构建 lockKey
     *
     * @param invocation     invocation
     * @param definitionKeys 定义
     * @return lockKey
     */
    @Override
    public String buildKey(MethodInvocation invocation, String[] definitionKeys) {
        StringBuilder sb = new StringBuilder();
        Method method = invocation.getMethod();
        sb.append(":").append(method.getDeclaringClass().getName()).append(".").append(method.getName()).append("#");
        if (definitionKeys.length > 1 || !"".equals(definitionKeys[0])) {
            sb.append(getSpelDefinitionKey(definitionKeys, method, invocation.getArguments()));
        }
        return sb.toString();
    }

    /**
     * 解析Spel表达式
     *
     * @param definitionKeys  参数名
     * @param method          方法
     * @param parameterValues 参数值
     * @return
     */
    protected String getSpelDefinitionKey(String[] definitionKeys, Method method, Object[] parameterValues) {
        EvaluationContext context = new MethodBasedEvaluationContext(null, method, parameterValues, NAME_DISCOVERER);
        List<String> definitionKeyList = new ArrayList<>(definitionKeys.length);
        for (String definitionKey : definitionKeys) {
            if (definitionKey != null && !definitionKey.isEmpty()) {
                String key = PARSER.parseExpression(definitionKey).getValue(context).toString();
                definitionKeyList.add(key);
            }
        }
        return StringUtils.collectionToDelimitedString(definitionKeyList, ".", "", "");
    }
}
